package xormplus

import (
	"errors"
	"gitee.com/hongzhaomin/hzm-common-go/coll"
)

type IPage[T any] interface {
	Limit() int
	Start() int
	GetTotal() int64
	GetRecords() []*T
	SetTotal(total int64)
	SetRecords(records []*T)
}

var _ IPage[any] = (*Page[any])(nil)

const (
	defaultCurrentPage = 1
	defaultPageSize    = 10
)

type Page[T any] struct {
	Records     []*T  `json:"records"`                                  // 查询数据列表
	Total       int64 `json:"total"`                                    // 总数
	CurrentPage int   `json:"currentPage" form:"currentPage,default=1"` // 当前页
	PageSize    int   `json:"pageSize" form:"pageSize,default=10"`      // 每页显示条数，默认 10
}

func (p *Page[T]) Limit() int {
	return p.PageSize
}

func (p *Page[T]) Start() int {
	return (p.CurrentPage - 1) * p.PageSize
}

func (p *Page[T]) GetTotal() int64 {
	return p.Total
}

func (p *Page[T]) GetRecords() []*T {
	return p.Records
}

func (p *Page[T]) SetTotal(total int64) {
	p.Total = total
}

func (p *Page[T]) SetRecords(records []*T) {
	p.Records = records
}

func NewDefaultPage[T any]() *Page[T] {
	return &Page[T]{
		CurrentPage: defaultCurrentPage,
		PageSize:    defaultPageSize,
	}
}

func NewPage[T any](beans []*T, total int64, currentPage int, pageSize int) *Page[T] {
	return &Page[T]{
		Records:     beans,
		Total:       total,
		CurrentPage: currentPage,
		PageSize:    pageSize,
	}
}

func ConvertPage[T any, R any](page IPage[T], convert func(t *T) *R) *Page[R] {
	if page == nil {
		panic(errors.New("page must not be nil"))
	}
	records := page.GetRecords()
	return &Page[R]{
		Records:     coll.ConvertEle(records, convert),
		Total:       page.GetTotal(),
		CurrentPage: FromStart(page.Start(), page.Limit()),
		PageSize:    page.Limit(),
	}
}

func FromStart(start int, pageSize int) int {
	return start/pageSize + 1
}
